package com.xyzh.application.config.wechat;


import com.xyzh.application.base.service.UserServiceImpl;
import lombok.Setter;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author ZJH
 * @since 2022/11/8
 * 实现授权的逻辑
 **/
@Setter
public class OpenIdAuthenticationProvider implements AuthenticationProvider {

    private final UserServiceImpl userDetailsService;

    private final PasswordEncoder passwordEncoder;

    public OpenIdAuthenticationProvider(UserServiceImpl userDetailsService, PasswordEncoder passwordEncoder) {
        this.userDetailsService = userDetailsService;
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public Authentication authenticate(Authentication authentication) {
        OpenIdAuthenticationToken authenticationToken = (OpenIdAuthenticationToken) authentication;
        String openId = (String) authenticationToken.getPrincipal();
        // 调用自定义的通过openId获取用户信息方法
        UserDetails user = userDetailsService.loadUserByOpenId(openId);
        if (null == user) {
            throw new InternalAuthenticationServiceException("openId错误");
        }

        OpenIdAuthenticationToken authenticationResult = new OpenIdAuthenticationToken(user, user.getAuthorities());
        authenticationResult.setDetails(authenticationToken.getDetails());
        return authenticationResult;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return OpenIdAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
